package cn.melon.view;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.image.BufferedImage;

import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;

/**
 * @ClassName: JTranslucentPanel
 * @author Hzy
 * 半透明的JPanel，由于每次要重绘背景，故在不断刷新中不会不断重叠失去透明的效果
 */
public class JTranslucentPanel extends JPanel{
    private int width,height;//size
    private Color color;//遮罩颜色
    private Point location;//在窗口中的相对位置
    private String bacPath;//背景图片路径
    public JTranslucentPanel(int width,int height,String bacPath,Color color){
        super();
        this.width = width;
        this.height = height;
        this.color = color;
        this.bacPath = bacPath;
        this.setPreferredSize(new Dimension(width,height));
    }
    @Override 
    public void paintComponent(Graphics g){
        Graphics2D g2d = (Graphics2D) g;
//      清空上次绘制的内容
      g2d.clearRect(0, 0, width, height);
//      绘制该JLabel的背景图像
      BufferedImage bacImg = new BufferedImage(width,height,BufferedImage.TYPE_4BYTE_ABGR);
      try{
//          bacImg = ImageIO.read(new File(bacPath));
          bacImg = ImageIO.read(this.getClass().getResource(bacPath));
      }catch(Exception e){
          e.printStackTrace();
      }
      JFrame root = (JFrame) this.getRootPane().getParent();
      this.location = new Point((this.getLocationOnScreen().x - root.getLocationOnScreen().x),(this.getLocationOnScreen().y-root.getLocationOnScreen().y));
      bacImg = bacImg.getSubimage(location.x,location.y,width,height);//绘制当前按钮背景为父容器相应位置的背景
      g2d.drawImage(bacImg, 0, 0, null);
      g2d.setColor(color);//半透明遮罩
      g2d.fillRect(0, 0, width, height);
    }
}
